package com.shaozi.nc.utils.spel;

import java.util.HashMap;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.shaozi.nc.data.model.SecretaryModel;


public class SecretarySpel {

	public SecretarySpel() {

	}

	/**
	 * 
	 * @param secretary
	 * @param userId
	 * @param commNames
	 *            params.put("fromUserName",
	 *            model.getEvalVariables().get("fromUserName"));
	 * @param bindUserIds
	 *            params.put("toUserName",
	 *            model.getEvalVariables().get("toUserName." +
	 *            user.getUserId()));
	 * @return
	 */
	public Map<String, Object> getSpelTitleParams(SecretaryModel secretary, String userId) {
		return getSpelParams(secretary.getTitleEvalVariables(), userId);
	}

	public Map<String, Object> getSpelContentParams(SecretaryModel secretary, String userId) {
		return getSpelParams(secretary.getContentEvalVariables(), userId);
	}

	public void addTitleEvalVariable(SecretaryModel model, String key, String val) {
		Map<String, Object> variables = model.getTitleEvalVariables();
		if (variables == null) {
			variables = new HashMap<>();
			model.setTitleEvalVariables(variables);
		}
		variables.put(key, val);
	}

	public void addContentEvalVariable(SecretaryModel model, String key, String val) {
		Map<String, Object> variables = model.getContentEvalVariables();
		if (variables == null) {
			variables = new HashMap<>();
			model.setContentEvalVariables(variables);
		}
		variables.put(key, val);
	}

	private Map<String, Object> getSpelParams(Map<String, Object> evalVariables, String userId) {
		if (evalVariables == null) {
			return null;
		}
		Map<String, Object> ret = new HashMap<>();
		boolean emptyUserId = StringUtils.isEmpty(userId);
		for (String key : evalVariables.keySet()) {
			String newKey = key;
			if (!emptyUserId && key.contains("_")) {
				if (!key.endsWith(userId)) {
					continue;
				}
				newKey = key.substring(0, key.indexOf("_"));
			}
			ret.put(newKey, evalVariables.get(key));

		}
		return ret;
	}

}
